package com.ikunikun.handler;

import com.ikunikun.constant.MessageConstant;
import com.ikunikun.exception.BaseException;
import com.ikunikun.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result<String> exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    /**
     * SQL语句异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        String message = ex.getMessage();
        log.error("异常信息：{}", message);
        if (message.contains("Duplicate entry") && message.contains("for key 'employee.idx_username'")){
            return Result.error(MessageConstant.USERNAME_EXISTS);
        } else if (message.contains("Duplicate entry") && message.contains("for key 'setmeal.idx_setmeal_name'")) {
            return Result.error(MessageConstant.SETMEAL_EXIST);
        }else {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
    }

}
